package threadjuc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/27 17:21
 * 测试监视器唤醒某个线程
 */
public class Juc6 {
    public static void main(String[] args) {
        Adds adds = new Adds();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                adds.printA();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                adds.printB();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                adds.printC();
            }
        },"C").start();
    }
}
class Adds {
    private int num = 1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void printA(){
        lock.lock();
        try{
            while (num!=1){
                condition1.await();
            }
            System.out.println("A");
            //通知B执行
            num = 2;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printB(){
        lock.lock();
        try{
            while (num!=2){
                condition2.await();
            }
            System.out.println("B");
            //通知B执行
            num = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();
        try{
            while (num!=3){
                condition3.await();
            }
            System.out.println("C");
            //通知B执行
            num = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
